<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<head>
    <title>题库管理</title>
    <block name="common" th:replace="common/base :: commonHead('林则徐小学教务管理系统')"></block>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery/jquery-1.8.3.min.js"></script>
    <!-- 引入EasyUI -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/easyui/1.4.4/._jquery.easyui.min.js"></script>
    <!-- 引入EasyUI的中文国际化js，让EasyUI支持中文 -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/easyui/1.4.4/locale/._easyui-lang-zh_CN.js"></script>
    <!-- 引入EasyUI的样式文件-->
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/easyui/1.4.4/themes/default/._easyui.css" type="text/css"/>
    <!-- 引入EasyUI的图标样式文件-->
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/easyui/1.4.4/themes/._icon.css" type="text/css"/>

</head>

<body class="easyui-layout" data-options="fit:true,border:false">
<div id="tb">
    <table style="width:100%">
        <tr>
            <td>
                <form id="searchForm">
                    <table class="searchTable" style="width:auto;" border="0">
                        <tr>
                            <td>
                                &nbsp;<label>题库题目：</label>
                                <input id="index" name="index" class="easyui-textbox"
                                       style="width: 150px;"/>
                            </td>
                        </tr>
                    </table>
                </form>
            </td>
    </table>

    <div>
        <table>
            <tr>
                <td>
                    <div>
                        <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-add"
                           onclick="addQuestion();">新增</a>&nbsp;
                        <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-search"
                           onclick="query();">查询</a>&nbsp;
                        <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-clear" onclick="reset();">重置</a>
                    </div>
                </td>
            </tr>
        </table>
    </div>
</div>
<input type="hidden" id="indexId" name="IndexId">
<table id="tt"></table>

<div id="addOptionDialog" class="easyui-dialog" title="添加选项"
     style="width: 800px; height: 600px;" data-options="modal:true" closed="true">
    <form id="addOptionForm" method="post">
        <div style="margin-top: 50px;margin-left: 30px;">
            <table class="grid">
                <tr>
                    <td>学校选择：</td>
                    <td>
                        <input id="whichSchoolId" name="whichSchoolId" class="easyui-combobox"
                               data-options="required:true,panelHeight:120" style="width: 150px;"/>
                    </td>
                </tr>
                <tr>
                    <td>问卷题目：</td>
                    <td>
                        <input id="topicT" name="topicT" type="text"
                               class="easyui-textbox" data-options="multiline:true,required:true,width:300,height:100"/>
                    </td>
                </tr>
                <tr>
                    <td>问卷选项：</td>
                    <td>
                        <a id="addQuestionOption" href="javascript:void(0);" class="easyui-linkbutton"
                           onclick="addOption()" style="width: 80px;height: 30px;margin-top: 20px;">添加选项</a>
                    </td>
                </tr>
            </table>
            <table id="optionTb"></table>
        </div>
    </form>
    <div style="text-align: center; padding: 5px 0;">
        <a id="saveKey" href="javascript:void(0);" class="easyui-linkbutton"
           onclick="saveAddIndex()" style="width: 80px;height: 30px;margin-top: 20px;">保存</a>
    </div>
</div>

<script type="text/javascript" th:inline="javascript">
    $(function () {
        queryList();
        optionTb();
        initSchoolCombobox();

    });
    var updateOrAdd = "";

    /*初始化学校*/
    function initSchoolCombobox() {
        $('#whichSchoolId').combobox({
            url: '/course/querySchoolCombobox',
            valueField: 'id',
            textField: 'organizationName'
        });
    }

    function queryList() {
        // $('#tt').datagrid({
        //     url: '/question/queryQuestionIndexList',
        //     toolbar: '#tb',
        //     loadMsg: '数据加载中,请稍后...',
        //     fit: true,
        //     striped: true,
        //     pagination: true,
        //     rownumbers: true,
        //     singleSelect: true,
        //     pageSize: 20,
        //     pageList: [10, 20, 30, 40, 50],
        //     // queryParams: $("#searchForm").serializeJSON(),
        //     columns: [
        //         [
        //             {field: 'id', title: '题目id', hidden: true},
        //             {
        //                 field: 'schoolName',
        //                 title: '学校',
        //                 width: '15%',
        //                 align: 'center',
        //                 halign: 'center'
        //             },
        //             {
        //                 field: 'index',
        //                 title: '题目',
        //                 width: '25%',
        //                 align: 'center',
        //                 halign: 'center'
        //             },
        //             {field: 'createTime', title: '创建时间', width: '15%', align: 'center', halign: 'center'},
        //             {field: 'createName', title: '创建人', width: '15%', align: 'center', halign: 'center'},
        //             {field: 'cz', title: '操作', width: '8%', align: 'center', halign: 'center', formatter: formatterCz}
        //         ]
        //     ],
        //     onClickRow: function (index, row) {
        //
        //     }
        // });
    }

    function formatterCz(value, row, index) {
        var a = '';
        a += '<a name="cz_btn" href="javascript:void(0)" data-options="plain:true,iconCls:\'icon-edit\'" onclick="editQuestionIndex(\'' + row.id + '\');">配置题目</a>&nbsp;';
        a += '<a name="cz_btn" href="javascript:void(0)" data-options="plain:true,iconCls:\'icon-cancel\'" onclick="removeQuestion(\'' + row.id + '\');">删除</a>&nbsp;';
        return a;
    }

    //查询
    function query() {
        $('#tt').datagrid('load', $("#searchForm").serializeJSON());
    }

    //关闭窗口
    function closeWin() {
        $('#addWin').dialog('close');
    }

    //重置
    function reset() {
        $('#searchForm').form('reset');
        query();
    }

    /*编辑题库模块*/
    function editQuestionIndex(id) {
        $("#indexId").val(id);
        updateOrAdd = "update";
        var data = [];
        loadCombData(data);
        $('#addOptionForm').form('clear');
        setOptionTb(id);
        $("#addOptionDialog").dialog("open");
    }

    function appendRowForEdit(id,optionCountEdit, orderNum, optionValue, optionSour) {

        var optionTb = $("#optionTb").datagrid('getRows');
        $('#optionTb').datagrid('appendRow', {
            id:id,
            optionOrder: String.fromCharCode(optionCountEdit),
            orderNum: orderNum,
            optionValue: optionValue,
            optionSour: optionSour
        });

        openRowEdit();
    }

    // //设置表格:回显
    function setOptionTb(id) {
        $.ajax({
                url: "/question/optionTbListEdit",
                dataType: "json",
                type: "POST",
                cache: false,
                data: {id: id},
                beforeSend: function (XMLHttpRequest) {
                    progressLoad();
                },
                success: function (data, textStatus, jqXHR) {
                    progressClose();
                    console.log("返回回来的集合" + JSON.stringify(data));
                    optionCount = 65;
                    orderNm = 1;
                    var editRow = data.optionTbListEdit;
                    for (var i = 0; i < editRow.length; i++) {
                        appendRowForEdit(editRow[i].id,optionCount, orderNm, editRow[i].index, editRow[i].indexSour);
                        optionCount++;
                        orderNm++;
                    }
                    $("#whichSchoolId").combobox("select", data.schoolId);
                    $("#topicT").textbox('setValue', data.index);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    progressClose();
                    $.messager.alert('提示', '请求列表错误', 'info');
                }
            }
        );
    }

    /*删除题库题目模块*/
    function removeQuestion(indexId) {
        $.messager.confirm("询问", "是否确定删除?", function (b) {
            if (b) {
                progressLoad();
                $.post("/question/removeQuestionIndex", {indexId: indexId}, function (data) {
                    progressClose();
                    if (data.result == 200) {
                        $.messager.alert('提示', data.message, 'info', function () {
                            query();
                        })

                    } else {
                        $.messager.alert('提示', data.message, 'info');
                        query();
                    }

                })
            }
        })
    }

    /*选项模块*/
    /*添加选项模块start*/
    function addQuestion() {
        updateOrAdd = "add";
        var data = [];
        loadCombData(data);
        $('#addOptionForm').form('clear');
        $("#addOptionDialog").dialog("open");
    }

    /*选项表格*/
    function optionTb() {
        // $('#optionTb').datagrid({
        //     loadMsg: '数据加载中,请稍后...',
        //     fit: true,
        //     striped: true,
        //     singleSelect: true,
        //     columns: [
        //         [
        //             {
        //                 field: 'id', title: 'id',hidden:true
        //             },
        //             {
        //                 field: 'optionOrder', title: '序号', width: '15%', align: 'center', halign: 'center'
        //             },
        //             {
        //                 field: 'orderNum', title: '排序'
        //             },
        //             {
        //                 field: 'optionValue', title: '选项', width: '25%', align: 'center', halign: 'center',
        //                 editor: {
        //                     type: 'textbox',
        //                     options: {
        //                         required: true
        //                     }
        //                 }
        //             },
        //             {
        //                 field: 'optionSour',
        //                 title: '选项分值',
        //                 width: '25%',
        //                 align: 'center',
        //                 halign: 'center',
        //                 editor: {
        //                     type: 'numberbox',
        //                     options: {
        //                         required: true,
        //                         min: 0
        //                     }
        //                 }
        //             },
        //             {field: 'cz', title: '操作', width: '25%', align: 'center', halign: 'center', formatter: addOptionFormatterCz}
        //         ]
        //     ]
        // });
    }

    function addOptionFormatterCz(value, row, index) {
        var a = '';
        a += '<a name="cz_btn" href="javascript:void(0)" data-options="plain:true,iconCls:\'icon-cancel\'" onclick="delCombRowById(\'' + row.optionOrder + '\');">删除</a>&nbsp;';
        return a;
    }

    function addOption() {
        appendRow();
    }

    var optionCount = 65;
    var orderNm = 1;

    function appendRow() {
        var optionTb = $("#optionTb").datagrid('getRows');
        if (optionTb.length == 0) {
            optionCount = 65;
            orderNm = 1;
        }
        $('#optionTb').datagrid('appendRow', {
            optionOrder: String.fromCharCode(optionCount),
            orderNum: orderNm,
            optionValue: '',
            optionSour: 0
        });
        optionCount++;
        orderNm++;
        openRowEdit();
    }
    //
    function openRowEdit() {
        var rows = $('#optionTb').datagrid('getRows');
        if (rows != null && rows.length > 0) {
            $.each(rows, function (index, row) {
                $('#optionTb').datagrid('beginEdit', index)
            });
        }
    }

    function delCombRowById(optionOrder) {
        closeRowEdit();
        optionCount = 65;
        orderNm = 1;
        var data = [];
        var rows = $('#optionTb').datagrid('getRows');
        if (rows != null && rows.length > 0) {
            $.each(rows, function (index, row) {
                if (row.optionOrder != optionOrder) {
                    row.optionOrder = String.fromCharCode(optionCount);
                    row.orderNum = orderNm;
                    optionCount++;
                    orderNm++;
                    data.push(row);
                }
            });
        }
        loadCombData(data);
    }

    function loadCombData(rows) {
        $('#optionTb').datagrid('loadData', rows);

        openRowEdit();
    }

    function closeRowEdit() {
        var rows = $('#optionTb').datagrid('getRows');
        if (rows != null && rows.length > 0) {
            $.each(rows, function (index, row) {
                $('#optionTb').datagrid('endEdit', index)
            });
        }
    }

    function saveAddIndex() {
        if (!$('#addOptionForm').form('validate')) {
            return;
        }
        closeRowEdit();
        //添加到主表
        var data = $("#addOptionForm").serializeJSON();
        var rows = $('#optionTb').datagrid('getRows');
        if (rows != null && rows.length > 0) {
            data.rows = rows;

            var url = "";
            if (updateOrAdd == "add") {
                url = "/question/addQuestionIndex";
            } else {
                url = "/question/updateQuestionIndex";
                data.indexId = $("#indexId").val();
            }
            console.log(data);
            console.log(JSON.stringify(data));
            $.ajax({
                url: url,
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                type: "POST",
                cache: false,
                data: JSON.stringify(data),
                beforeSend: function (XMLHttpRequest) {
                    progressLoad();
                },
                success: function (data, textStatus, jqXHR) {
                    progressClose();
                    if (data.result == 200) {
                        $.messager.alert('提示', data.message, 'info', function () {
                            //善后
                            var data = [];
                            loadCombData(data);
                            $('#addOptionForm').form('clear');
                            $("#addOptionDialog").dialog("close");
                            optionCount = 65;
                            orderNm = 1;
                            query();
                        });
                    } else {
                        $.messager.alert('提示', data.message, 'info');
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    progressClose();
                    $.messager.alert('提示', '请求错误', 'info');
                }
            });

        } else {
            $.messager.alert('提示', '请添加选项', 'info');
        }
    }
</script>
</body>
</html>
